
package com.ld.security.common.mybatis.core.handlers;

import com.ld.security.common.core.base.column.SuperColumn;
import com.ld.security.common.core.util.GenericUtil;
import com.ld.security.common.core.util.JsonUtil;
import com.ld.security.common.core.util.ReflectionUtil;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;


public abstract class JsonTypeHandler<E extends SuperColumn> extends BaseTypeHandler<E> {

    private Class<E> clazz = this.getEntityClass();


    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, E parameter, JdbcType jdbcType) throws SQLException {
        String json = parameter.getValue();
        ps.setString(i,json);
    }

    @Override
    public E getNullableResult(ResultSet rs, String columnName) throws SQLException {
        String json = rs.getString(columnName);
        E v ;
        if(json == null){
            v = ReflectionUtil.newInstance(clazz);
        }else{
            v =  JsonUtil.toObject(json,clazz);
        }

        return v;
    }

    @Override
    public E getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        String json = rs.getString(columnIndex);
        E v ;
        if(json == null){
            v = ReflectionUtil.newInstance(clazz);
        }else{
            v =  JsonUtil.toObject(json,clazz);
        }

        return v;
    }

    @Override
    public E getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        String json = cs.getString(columnIndex);
        E v ;
        if(json == null){
            v = ReflectionUtil.newInstance(clazz);
        }else{
            v =  JsonUtil.toObject(json,clazz);
        }

        return v;
    }


    /**
     * 得到泛型
     * @return
     */
    protected Class<E> getEntityClass()
    {
        return (Class<E>) GenericUtil.getGeneric(this.getClass(), JsonTypeHandler.class, 0);
    }
}
